/**
 * 基础网络请求
 */
class requestnet {
  constructor() {
    this._header = {}
  }
  /**
 * 设置统一的异常处理，比如登陆状态校验
 */
  setErrorHandler(handler) {
    this._errorHandler = handler;
  }
  //get请求
  sendGetRequest(url, data = {}) {
    this._header = { 
      'Content-Type': 'application/json',
      'Authorization': wx.getStorageSync("token") 
    }
    return this.sendRequest(url, data, this._header, 'GET')
  }
  //post请求上传form表单
  sendPostFormRequest(url, data = {}) {
    this._header = { "Content-Type": "application/x-www-form-urlencoded" }
    return this.sendRequest(url, data, this._header, 'POST')
  }
  //post请求上传json
  sendPostJsonRequest(url, data = {}) {
    this._header = {
      "Content-Type": "application/json"
    }
    return this.sendRequest(url, data, this._header, 'POST')
  }
  //post请求上传json
  postTokenFormRequest(url, data = {}) {
    this._header = { 
      "Content-Type": "application/x-www-form-urlencoded",
      'authorization': wx.getStorageSync("token")
     }
    return this.sendRequest(url, data, this._header, 'POST')
  }
    //post请求上传json
    postTokenJsonRequest(url, data = {}) {
      this._header = { 
        "Content-Type": "application/json",
        'authorization': wx.getStorageSync("token")
       }
      return this.sendRequest(url, data, this._header, 'POST')
    }
  //网络请求的工具类
  sendRequest(url, data = {}, header = this._header, method = 'GET') {
    return new Promise((resolve, reject) => {
      var that = this;
      wx.request({
        url: url,
        data: data,
        method: method,
        header: header,
        success: function (res) {
          if (res.statusCode === 200) {
            //200: 服务端业务处理正常结束
            resolve(res);
          } else {
            //200以外的code可以单独处理了
            if (that._errorHandler != null) {
              that._errorHandler(res)
            }
            reject(res)
          }
        },
        fail: function (res) {
          //异常拦截
          if (that._errorHandler != null) {
            that._errorHandler(res)
          }
          reject(res)
        },
        complete: function (res) {

        }
      })
    })
  }
}

export default requestnet
